<?php
use SampleModel\MysqlAccessor;
use SampleModel\Model;
use SampleModel\Config;

class MysqlAccessorTest extends PHPUnit_Framework_TestCase
{
    public static function setUpBeforeClass()
    {
        $dataBaseConfig = array(
            'default' => array(
                'dsn' => 'mysql:dbname=sample_model_test;host=127.0.0.1',
                'userName' => 'root',
                'password' => '',
                'driverOptions' => array(
                    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
                    Pdo::ATTR_ERRMODE => Pdo::ERRMODE_EXCEPTION,
                )
            )
        );
        Config::register($dataBaseConfig);
    }

    public function testInsert()
    {
        $model = TestModel::create(array(
            'userName' => 'Jackin',
            'password' => md5('Mr.Jackin'),
            'createTime' => date('Y-m-d H:i:s'),
        ), 'test');
        $this->assertEquals($model->save(), 1);
    }

    public function testFind()
    {
        $userInfo = TestModel::findById(1);
    }

}

class TestModel extends Model
{
    public static function getMapping($splitSuffix = '')
    {
        return array(
            'table' => 'members_' . $splitSuffix,
            'key' => 'id',
            'columns' => array(
                'id' => 'id',
                'userName' => 'user_name',
                'password' => 'password',
                'updateTime' => 'update_time',
                'createTime' => 'create_time',
            ),
        );
    }

    /**
     * @param $id
     * @return null|Model
     */
    public static function findById($id)
    {
        $dataAccess = static::dataAccessor('test');
        $dataAccess->filter('id', $id);
        $dataAccess->sort('id');
        $dataAccess->limit(1);
        $result = $dataAccess->find();
        if (count($result) == 1) {
            return $result[0];
        }
        return null;
    }
}